package com.fuchuang.seckillsystem.service.impl;

import com.fuchuang.seckillsystem.dto.KeyConstants;
import com.fuchuang.seckillsystem.entity.Account;
import com.fuchuang.seckillsystem.exception.GlobalException;
import com.fuchuang.seckillsystem.mapper.AccountMapper;
import com.fuchuang.seckillsystem.service.IAccountService;
import com.fuchuang.seckillsystem.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class AccountServiceImpl implements IAccountService {
    
    @Resource
    private AccountMapper accountMapper;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    
    @Override
    public Account getAccountByUserId(Integer userId) {
        Account account = (Account) redisTemplate.opsForHash().get(KeyConstants.ACCOUNT, String.valueOf(userId));
        if (account == null) {
            account = accountMapper.selectAccountByUserId(userId);
        }
        return account;
    }
    
    @Override
    public void updateAccount(Account account) {
        int rows = accountMapper.updateByPrimaryKeySelective(account);
        if (rows != 1) {
            throw new GlobalException(RespBeanEnum.ORDER_PAY_ERROR);
        }
        redisTemplate.opsForHash().delete(KeyConstants.ACCOUNT, String.valueOf(account.getUserId()));
    }
    
    @Override
    public void updateBankAccount(BigDecimal payPrice) {
        Integer rows = accountMapper.updateBankAccount(payPrice);
        if (rows != 1) {
            throw new GlobalException(RespBeanEnum.ORDER_PAY_ERROR);
        }
    }
    
    @Override
    public Account getBankAccount() {
        return accountMapper.selectAccountByUserId(0);
    }
}
